package controllers

import dao._
import play.api.i18n.I18nSupport

import javax.inject.Inject
import play.api.mvc.{AbstractController, ControllerComponents}
import tool.{FileTool, FormTool, Tool}
import models.Tables._

import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.Future
import implicits.Implicits._
import play.api.libs.json.Json
import utils.Utils

import java.io.File

/**
 * Created by yz on 3/7/2020
 */
class AdminController  @Inject()(cc: ControllerComponents)(
                                implicit val accountDao:AccountDao,
                                implicit val keggInfoDao: KeggInfoDao,
                                implicit val modeDao: ModeDao,
) extends AbstractController(cc) with I18nSupport{

  def metaboDbManageBefore = Action { implicit request =>
    Ok(views.html.admin.metaboDbManage())
  }

  def logout = Action { implicit request =>
    Redirect(routes.AppController.loginBefore).flashing("info" -> "退出登录成功!").removingFromSession("admin")
  }

  def changePasswordBefore = Action { implicit request =>
    Ok(views.html.admin.changePassword())
  }

  def changePassword = Action.async { implicit request =>
    val data = FormTool.changePasswordForm.bindFromRequest().get
    accountDao.selectById1.flatMap { x =>
      if (data.password == x.password) {
        val row = AccountRow(x.id, x.account, data.newPassword)
        accountDao.update(row).map { y =>
          Redirect(routes.AppController.loginBefore).flashing("info" -> "密码修改成功!").removingFromSession("admin")
        }
      } else {
        Future.successful(Redirect(routes.AdminController.changePasswordBefore).flashing("info" -> "用户名或密码错误!"))
      }
    }
  }

  def getAllMetaboDb = Action.async { implicit request =>
    keggInfoDao.selectAll.map { keggInfos =>
      val sortRows = if (keggInfos.forall(x => x.index.isInt)) {
        keggInfos.sortBy(_.index.toInt)
      } else keggInfos
      val array = Utils.getArrayByTs(sortRows)
      val columnNames = List("index", "name", "strandardName", "superclass", "accession", "keggid")
      val json = ujson.Obj("columnNames" -> columnNames, "array" -> array)
      Ok(json)
    }
  }

  def updateMetaboDb = Action.async(parse.multipartFormData) { request =>
    val file = request.body.file("file").get
    val tmpDir = Tool.createTempDirectory("tmpDir")
    val tmpFile = new File(tmpDir, "tmp.xlsx")
    file.ref.moveTo(tmpFile, true)
    val myMessage = FileTool.metaboFileCheck(tmpFile)
    if (!myMessage.valid) {
      Tool.deleteDirectory(tmpDir)
      Future.successful(Ok(Json.obj("error" -> myMessage.message)))
    } else {
      val lines = tmpFile.xlsxLines()
      val headers = lines.head
      val keggInfos = lines.drop(1).mapOtherByColumns { columns =>
        val lineMap = headers.zip(columns).toMap
        val name = lineMap("Name")
        val strandardName = lineMap("Standard.name")
        KeggInfoRow(lineMap("Index"), name, strandardName, lineMap.getOrElse("HMDBID", "NA"),
          lineMap.getOrElse("KeggID", "NA"), lineMap("Class"))
      }
      keggInfoDao.updates(keggInfos).map { x =>
        Tool.deleteDirectory(tmpDir)
        Ok(Json.toJson("success!"))
      }
    }
  }



}
